<?php
/**
 * html代码生成器
 */

namespace app\common\model;

use think\Cache;

class FieldLogic
{
    private $cmsMoudleCache;
    private $FieldCache;
    private $cmsFieldModel;

    public function __construct($tableName)
    {
        $this->cmsMoudleCache = Cache::get('moudle');
        $this->FieldCache = Cache::get($tableName);
        $this->cmsFieldModel = new FieldModel();
    }

    /**
     * 编辑与修改动作时根据不同字段类型获取界面
     * @return string
     */
    public function getHtml($data=[])
    {
        $field = [];
        $layout = [];
        foreach ($this->FieldCache as $k => $v) {
            if ($v['enable'] == 0) { //不处理禁用字段
                continue;
            }
            $field[] = $v;
            $layout[] = $v['set']['layout'];
        }
        /**计算form布局 begin**/
        $layout = implode('', $layout);
        $count = substr_count($layout, '22', 0); //计算22出现次数
        $two = []; //双列布局出现位置
        $i = 0;
        while ($i < $count) {
            $pos = strpos($layout, '22');
            $layout = str_replace_limit('22', '11', $layout, 1);
            if ($pos >= 0) {
                $two[] = $pos;
                $i++;
            } else {
                break;
            }
        }
        $layoutForm = [];
        $size = count($field);
        for ($i = 0; $i < $size; $i++) {  //重组field数量
            if (in_array($i, $two)) {
                $layoutForm[] = [$field[$i], $field[$i + 1]];
                $i += 1; //跳一级
            } else {
                $layoutForm[] = [$field[$i]];
            }
        }
        /**计算form布局 end**/
        foreach ($layoutForm as $oneKey => $one) {
            foreach ($one as $twoKey => $two) {
                $value = $this->getDefault($two, $data);
                //处理函数
                $function = '_' . $two['field_type'];
                $h = $this->$function($two, $value); //当前表单
                $layoutForm[$oneKey][$twoKey]['html'] = $h;
            }
        }
        return $layoutForm;
    }

    /**
     * 获取默认值
     * @param $fieldName
     * @param $set
     * @param $data
     * @return string
     */
    private function getDefault($field, $data)
    {
        $set = $field['set'];
        if(in_array($field['field_type'],['cid','tpl','input','number','box','textarea','datetime'])){ //带{}模板标签
            if (empty($data)) {
                if (array_key_exists('default', $set)) {
                    $value = $set['default'];
                } else {
                    $value = '';
                }
            } else {
                $value = "{\$info['{$field['field_name']}']}";
            }
        }else{ //widget类型控件
            if (empty($data)) {
                if (array_key_exists('default', $set)) {
                    $value = "'".$set['default']."'";
                } else {
                    $value = '\'\'';
                }
            } else {
                $value = "\$info['{$field['field_name']}']";
            }
        }
        return $value;
    }

    /**
     * 根据验证规则返回html验证字符
     * @param $validate
     * @return string
     */
    private function getValidRule($validate)
    {
        $ignore = '';
        if (empty($validate)) {
            return '';
        }
        if (!in_array('require', $validate)) { //非必填项
            $ignore = ' ignore="ignore"';
        }
        $datatypeArr = [];
        foreach ($validate as $v) {
            switch ($v) {
                case 'require':
                    $datatypeArr[] = '*';
                    break;
                case 'number':
                    $datatypeArr[] = 's';
                    break;
                case 'email':
                    $datatypeArr[] = 'e';
                    break;
                case 'url':
                    $datatypeArr[] = 'url';
                    break;
                default:
                    break;
            }
        }
        if (empty($datatypeArr)) {
            return '';
        }
        $datatype = 'datatype="' . implode(',', $datatypeArr) . '"';
        return $datatype . $ignore;
    }

    /**
     * 栏目
     * @param $field
     * @param $value
     * @return string
     */
    public function _cid($field, $value)
    {
        $set = $field['set'];
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    <select name="cid" id="cid" datatype="*" class="form-control">
        <option value=''>==选择栏目==</option>
        {volist name="category" id="vo"}
        <option value='{\$vo.cid}' {\$vo.disabled} {\$vo.selected}>{\$vo._name}</option>
        {/volist}
    </select>
</div>
CODE;
        return $html;
    }

    /**
     * 模版框
     * @param $field
     * @param $value
     * @return string
     */
    public function _tpl($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        if (empty($value)) {
            $value = str_replace('cms_', '', 'show_' . $this->cmsMoudleCache[$field['mid']]['table_name']);
        }
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    <input class="form-control" type="text" placeholder="{$field['tips']}" name="{$field['field_name']}" value="{$value}" {$validateRule} />
</div>
CODE;
        return $html;
    }

    /**
     * 文本框
     * @param $field
     * @param $value
     * @return string
     */
    public function _input($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    <input class="form-control" type="text" placeholder="{$field['tips']}" name="{$field['field_name']}" value="{$value}" {$validateRule} />
</div>
CODE;
        return $html;
    }
    /**
     * 数字框
     * @param $field
     * @param $value
     * @return string
     */
    public function _number($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    <input class="form-control" type="text" placeholder="{$field['tips']}" name="{$field['field_name']}" value="{$value}" {$validateRule} />
</div>
CODE;
        return $html;
    }

    /**
     * 多行文本框
     * @param $field
     * @param $value
     * @return string
     */
    public function _textarea($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        $html=<<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    <textarea class="form-control" rows="3" name="{$field['field_name']}" {$validateRule}>{$value}</textarea>
</div>
CODE;
        return $html;
    }

    /**
     * 日期时间
     * @param $field
     * @param $value
     * @return string
     */
    public function _datetime($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前端不验证
        $jsFormat = [0 => "laydatetime", 1 => "laydate", 2 => "time"];
        $datecss = $jsFormat[$set['format']];
        $html=<<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    <input class="form-control {$datecss}" type="text" placeholder="{$field['tips']}" name="{$field['field_name']}" value="{$value}" />
</div>
<script>formatDate();</script>
CODE;
        return $html;
    }

    /**
     * 富文本
     * @param $field
     * @param $value
     * @return string
     */
    public function _editor($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html=<<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    {:widget('common/Form/ueditor',['{$field['field_name']}',{$value},\$uid])}
</div>
CODE;
        return $html;
    }

    /**
     * 选项
     * @param $field
     * @param $value
     * @return string
     */
    public function _box($field, $value)
    {
        $set = $field['set'];
        //表单值
        $_v = explode(",", $set['options']);
        $options = [];
        foreach ($_v as $p) {
            $p = explode("|", $p);
            $options[$p[0]] = $p[1];
        }
        $h = '';
        //select添加select
        if ($set['form_type'] == 'select') {
            $h .= "<select name=\"{$field['field_name']}\" class=\"form-control\">";
        }
        $type="add";
        if(substr ($value, 0,2)=='{$'){ //编辑动作
            $type="edit";
        }
        //{$info['is_recommend']}
        foreach ($options as $v => $text) {
            switch ($set['form_type']) {
                case "radio" :
                    if($type=='add'){
                        $checked = $value == $v ? 'checked' : '';
                    }else{ //编辑动作
                        $checked = "{eq name=\"info.{$field['field_name']}\" value=\"$v\"}checked{/eq}";
                    }
                    $h .= "<label class=\"radio-inline i-checks\"><input type='radio' name=\"{$field['field_name']}\" value=\"{$v}\" {$checked}/> {$text}</label>";
                    break;
                case "checkbox" :
                    if($type=='add'){
                        $checked = in_array($v, (array)$value) ? 'checked' : '';
                    }else{ //编辑动作
                        $checked = "{in name=\"{$v}\" value=\"\$info[{$field['field_name']}]\"}checked{/in}";
                    }
                    $h .= "<label class=\"checkbox-inline i-checks\"><input type='checkbox' name=\"{$field['field_name']}[]\" value=\"{$v}\" {$checked}/> {$text}</label> ";
                    break;
                case "select" :
                    if($type=='add'){
                        $selected = $value == $v ? 'selected' : '';
                    }else{ //编辑动作
                        $selected = "{eq name=\"info.{$field['field_name']}\" value=\"$v\"}checked{/eq}";
                    }
                    $h .= "<option name=\"{$field['field_name']}\" value=\"{$v}\" {$selected}> {$text}</option>";
                    break;
            }
        }
        if ($set['form_type'] == 'select') {
            $h .= "</select>";
        }
        $html = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= $h;
        $html .= '</div>';
        return $html;
    }

    /**
     * 单图上传
     * @param $field
     * @param $value
     * @return string
     */
    public function _image($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    {:widget('common/Form/singleImg',['{$field['field_name']}',{$value},\$uid])}
</div>
CODE;
        return $html;
    }

    /**
     * 多图上传
     * @param $field
     * @param $value
     */
    public function _images($field, $value)
    {
        $set = $field['set'];
        $value = empty($value) ? '' : $value;
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $widgethtml='';
        if ($set['type'] == 'images') {
            $widgethtml = <<<CODE
    {:widget('common/Form/moreImg',['{$field['field_name']}',{$value},\$uid])}
CODE;
        }
        if ($set['type'] == 'imagesForm') {
            $widgethtml = <<<CODE
    {:widget('common/Form/moreTextImg',['{$field['field_name']}',{$value},\$uid])}
CODE;
        }
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    {$widgethtml}
</div>
CODE;
        return $html;
    }

    /**
     * 单附件上传
     * @param $field
     * @param $value
     */
    public function _file($field, $value)
    {
        $set = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    {:widget('common/Form/singleFile',['{$field['field_name']}',{$value},\$uid])}
</div>
CODE;
        return $html;
    }

    /**
     * 多附件上传
     * @param $field
     * @param $value
     */
    public function _files($field, $value)
    {
        $set = $field['set'];
        $value = empty($value) ? '' : $value;
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    {:widget('common/Form/moreFile',['{$field['field_name']}',{$value},\$uid])}
</div>
CODE;
        return $html;
    }

    /**
     * 自定义方法
     * @param $field
     * @param $value
     */
    public function _custom($field, $value)
    {
        $set = $field['set'];
        $custom = explode('|', $set['custom']);
        $html = <<<CODE
<label class="col-sm-2 control-label Validform_label">{$field['title']}</label>
<div class="col-sm-{$set['size']}">
    {:widget('{$custom[1]}',['{$field['field_name']}',{$value},'{$set['custom']}'])}
</div>
CODE;
        return $html;
    }
}
